package sdl2_impl

import (
	"code.google.com/p/go8/games"
	"github.com/gonutz/go-sdl2/sdl"
)

type Keyboard struct {
	keyMap       map[sdl.Keycode]uint8
	down         [16]bool
	aKeyIsQueued bool
	queue        uint8
}

func NewKeyboard() *Keyboard {
	return &Keyboard{}
}

func (k *Keyboard) KeyDown(which uint8) bool {
	return k.down[int(which)]
}

func (k *Keyboard) LastKey() (bool, uint8) {
	return k.aKeyIsQueued, k.queue
}

func (k *Keyboard) ClearLastKey() { k.aKeyIsQueued = false }

func (k *Keyboard) HandleKeyDown(key sdl.Keycode) {
	if key, hasIt := k.keyMap[key]; hasIt {
		k.down[key] = true
		if !k.aKeyIsQueued {
			k.queue = key
			k.aKeyIsQueued = true
		}
	}
}

func (k *Keyboard) HandleKeyUp(key sdl.Keycode) {
	if key, hasIt := k.keyMap[key]; hasIt {
		k.down[key] = false
	}
}

var gameKeyToSdlKeyMap map[games.GameKey][]sdl.Keycode

func init() {
	gameKeyToSdlKeyMap = map[games.GameKey][]sdl.Keycode{
		games.Left:    []sdl.Keycode{sdl.K_LEFT},
		games.Right:   []sdl.Keycode{sdl.K_RIGHT},
		games.Up:      []sdl.Keycode{sdl.K_UP},
		games.Down:    []sdl.Keycode{sdl.K_DOWN},
		games.Enter:   []sdl.Keycode{sdl.K_RETURN, sdl.K_RETURN2},
		games.Space:   []sdl.Keycode{sdl.K_SPACE},
		games.Number0: []sdl.Keycode{sdl.K_0, sdl.K_KP_0},
		games.Number1: []sdl.Keycode{sdl.K_1, sdl.K_KP_1},
		games.Number2: []sdl.Keycode{sdl.K_2, sdl.K_KP_2},
		games.Number3: []sdl.Keycode{sdl.K_3, sdl.K_KP_3},
		games.Number4: []sdl.Keycode{sdl.K_4, sdl.K_KP_4},
		games.Number5: []sdl.Keycode{sdl.K_5, sdl.K_KP_5},
		games.Number6: []sdl.Keycode{sdl.K_6, sdl.K_KP_6},
		games.Number7: []sdl.Keycode{sdl.K_7, sdl.K_KP_7},
		games.Number8: []sdl.Keycode{sdl.K_8, sdl.K_KP_8},
		games.Number9: []sdl.Keycode{sdl.K_9, sdl.K_KP_9},
		games.KeyA:    []sdl.Keycode{sdl.K_a},
		games.KeyB:    []sdl.Keycode{sdl.K_b},
		games.KeyC:    []sdl.Keycode{sdl.K_c},
		games.KeyD:    []sdl.Keycode{sdl.K_d},
		games.KeyE:    []sdl.Keycode{sdl.K_e},
		games.KeyF:    []sdl.Keycode{sdl.K_f},
		games.KeyQ:    []sdl.Keycode{sdl.K_q},
	}
}

func (k *Keyboard) SetKeyMap(keys map[games.GameKey]uint8) {
	k.keyMap = make(map[sdl.Keycode]uint8)
	for gameKey, chip8Key := range keys {
		for _, sdlKey := range gameKeyToSdlKeyMap[gameKey] {
			k.keyMap[sdlKey] = chip8Key
		}
	}
}
